package com.xbongbong.pro.dataset.helper;

import com.google.common.collect.Maps;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author gzt
 * @version 1.0
 * @Description -
 * @datetime - 2022/6/28-11:20
 * @since v1.0
 */
public class MapHelper {

    /**
     * @author  gzt
     * @Description 获取LinkedHashMap最后一个元素key
     * @Date 11:22 2022/6/28
     * @param map
     * @return java.util.Map.Entry
     * @throws NoSuchFieldException, IllegalAccessException
     **/

    public static String getTailKeyByReflection(Map map)
            throws NoSuchFieldException, IllegalAccessException {
        Field tail = map.getClass().getDeclaredField("tail");
        tail.setAccessible(true);
        Map.Entry entry = (Map.Entry) tail.get(map);
        if (Objects.nonNull(entry) && Objects.nonNull(entry.getKey())) {
            return entry.getKey().toString();
        }
        return null;
    }

    /**
     * @author  gzt
     * @Description  获取LinkedHashMap最后一个元素value
     * @Date 14:06 2022/6/28
     * @param map
     * @return java.lang.String
     * @throws NoSuchFieldException, IllegalAccessException
     **/

    public static String getTailValueByReflection(Map map)
            throws NoSuchFieldException, IllegalAccessException {
        Field tail = map.getClass().getDeclaredField("tail");
        tail.setAccessible(true);
        Map.Entry entry = (Map.Entry) tail.get(map);
        if (Objects.nonNull(entry) && Objects.nonNull(entry.getValue())) {
            return String.valueOf(entry.getValue());
        }
        return null;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        LinkedHashMap<Object, Object> linkedHashMap = Maps.newLinkedHashMap();
        linkedHashMap.put(1,"q");
        linkedHashMap.put(2,"qs");
    }
}
